import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { getProfile, logout, toggleSpace, generateModel, uploadModel, getMyModels, deleteModel } from '../api'
import ModelGenerator from '../components/ModelGenerator'
import ModelList from '../components/ModelList'

function Dashboard({ onLogout }) {
    const [profile, setProfile] = useState(null)
    const [models, setModels] = useState([])
    const [showGenerator, setShowGenerator] = useState(false)
    const navigate = useNavigate()

    useEffect(() => {
        loadProfile()
        loadModels()
    }, [])

    // 监听模型生成状态
    useEffect(() => {
        // 检查是否有正在生成的模型
        const hasGenerating = models.some(m => m.status === 'generating')

        if (!hasGenerating) return

        // 每5秒轮询一次
        const interval = setInterval(() => {
            console.log('🔄 检查模型生成状态...')
            loadModels()
        }, 5000)

        return () => clearInterval(interval)
    }, [models])

    const loadProfile = async () => {
        try {
            const res = await getProfile()
            setProfile(res.data)
        } catch (err) {
            console.error(err)
        }
    }

    const loadModels = async () => {
        try {
            const res = await getMyModels()
            // 按创建时间降序排序（最新的在前）
            const sortedModels = (res.data || []).sort((a, b) => {
                return new Date(b.created_at) - new Date(a.created_at)
            })
            setModels(sortedModels)
        } catch (err) {
            console.error(err)
        }
    }

    const handleLogout = async () => {
        try {
            await logout()
            onLogout()
            navigate('/login')
        } catch (err) {
            console.error(err)
        }
    }

    const handleToggleSpace = async () => {
        try {
            await toggleSpace(!profile.space_enabled)
            loadProfile()
        } catch (err) {
            console.error(err)
        }
    }

    const handleGenerate = async (data) => {
        try {
            await generateModel(data)
            setShowGenerator(false)
            // 立即刷新模型列表，开始监听
            await loadModels()
        } catch (err) {
            alert(err.response?.data?.error || '生成失败')
        }
    }

    const handleUpload = async (formData) => {
        try {
            await uploadModel(formData)
            setShowGenerator(false)
            alert('上传成功')
            loadModels()
        } catch (err) {
            alert(err.response?.data?.error || '上传失败')
        }
    }

    const handleDelete = async (id) => {
        if (!confirm('确定删除此模型？')) return
        try {
            await deleteModel(id)
            loadModels()
        } catch (err) {
            alert('删除失败')
        }
    }

    if (!profile) {
        return (
            <div className="flex justify-center items-center h-screen bg-dark-900">
                <div className="text-center">
                    <div className="inline-block animate-spin rounded-full h-12 w-12 border-4 border-blue-600 border-t-transparent"></div>
                    <p className="mt-4 text-gray-400">加载中...</p>
                </div>
            </div>
        )
    }

    return (
        <div className="min-h-screen bg-dark-900">
            {/* Header */}
            <header className="bg-dark-800 border-b border-dark-700 sticky top-0 z-10 backdrop-blur-sm bg-dark-800/80">
                <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-4">
                    <div className="flex justify-between items-center">
                        <h1 className="text-2xl font-bold bg-gradient-to-r from-blue-500 to-blue-700 bg-clip-text text-transparent">
                            🏛️ 记忆宫殿
                        </h1>
                        <div className="flex items-center gap-4">
                            <span className="text-gray-400">欢迎，<span className="text-blue-500 font-medium">{profile.username}</span></span>
                            <button onClick={handleLogout} className="btn-secondary">
                                登出
                            </button>
                        </div>
                    </div>
                </div>
            </header>

            {/* Main Content */}
            <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                <div className="grid grid-cols-1 lg:grid-cols-3 gap-6 mb-8">
                    {/* Profile Card */}
                    <div className="lg:col-span-1">
                        <div className="card">
                            <h2 className="text-xl font-semibold mb-4 text-gray-100">个人信息</h2>
                            <div className="space-y-3">
                                <div>
                                    <span className="text-gray-400 text-sm">用户名</span>
                                    <p className="text-gray-100 font-medium">{profile.username}</p>
                                </div>
                                <div>
                                    <span className="text-gray-400 text-sm">宫殿状态</span>
                                    <p className="flex items-center gap-2">
                                        <span className={`inline-block w-2 h-2 rounded-full ${profile.space_enabled ? 'bg-green-500' : 'bg-gray-500'}`}></span>
                                        <span className="text-gray-100 font-medium">
                                            {profile.space_enabled ? '已开启' : '已关闭'}
                                        </span>
                                    </p>
                                </div>
                                {profile.space_enabled && (
                                    <div>
                                        <span className="text-gray-400 text-sm">宫殿链接</span>
                                        <a
                                            href={profile.space_url}
                                            target="_blank"
                                            rel="noopener noreferrer"
                                            className="block text-blue-500 hover:text-blue-400 text-sm break-all transition-colors"
                                        >
                                            {window.location.origin}{profile.space_url}
                                        </a>
                                    </div>
                                )}
                            </div>
                            <button
                                onClick={handleToggleSpace}
                                className={`w-full mt-6 ${profile.space_enabled ? 'btn-secondary' : 'btn-primary'}`}
                            >
                                {profile.space_enabled ? '关闭宫殿' : '开启宫殿'}
                            </button>
                        </div>
                    </div>

                    {/* Stats Cards */}
                    <div className="lg:col-span-2 grid grid-cols-1 sm:grid-cols-2 gap-6">
                        <div className="card">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-gray-400 text-sm">模型总数</p>
                                    <p className="text-3xl font-bold text-blue-500 mt-1">{models.length}</p>
                                </div>
                                <div className="w-12 h-12 bg-blue-600/20 rounded-lg flex items-center justify-center">
                                    <span className="text-2xl">📦</span>
                                </div>
                            </div>
                        </div>
                        <div className="card">
                            <div className="flex items-center justify-between">
                                <div>
                                    <p className="text-gray-400 text-sm">宫殿访问</p>
                                    <p className="text-3xl font-bold text-blue-500 mt-1">
                                        {profile.space_enabled ? '公开' : '私密'}
                                    </p>
                                </div>
                                <div className="w-12 h-12 bg-blue-600/20 rounded-lg flex items-center justify-center">
                                    <span className="text-2xl">🏛️</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                {/* Models Section */}
                <div className="card">
                    <div className="flex justify-between items-center mb-6">
                        <h2 className="text-xl font-semibold text-gray-100">我的模型</h2>
                        <button onClick={() => setShowGenerator(true)} className="btn-primary">
                            ✨ 生成新模型
                        </button>
                    </div>

                    <ModelList models={models} onDelete={handleDelete} onRefresh={loadModels} />
                </div>
            </div>

            {/* Model Generator Modal */}
            {showGenerator && (
                <ModelGenerator
                    onGenerate={handleGenerate}
                    onUpload={handleUpload}
                    onClose={() => setShowGenerator(false)}
                />
            )}
        </div>
    )
}

export default Dashboard
